package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.mapper.RoleMapper;
import com.daoliuhe.scaffold.model.Role;
import com.daoliuhe.scaffold.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

	private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
	@Autowired
	RoleMapper roleMapper;

	@Override
	public Role getById(String id) {
		logger.info("getById,id:{}",id);
		return roleMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void saveOrUpdate(Role role) {
		logger.info("saveOrUpdate,role:{}",role);
		if (!StringUtils.isEmpty(role.getId())) {
			roleMapper.updateByPrimaryKey(role);
		} else {
			roleMapper.insert(role);
		}
	}
	
	@Override
	public Map<String, Object> getPageData(Role role) {
		logger.info("getPageData,role:{}",role);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", roleMapper.getPageCount(role));
		map.put("rows", roleMapper.getPageData(role));
		return map;
	}
	
	public boolean isRightName(String name, String id) {
		logger.info("isRightName,name:{},id:{}",name,id);
		boolean flag = false;
		if (StringUtils.isEmpty(id)) {
			flag = roleMapper.selectByName(name) == null;
		} else {
			Role role = roleMapper.selectByPrimaryKey(id);
			if (role != null) {
				flag = role.getName().equals(name);
				if (!flag) {
					flag = roleMapper.selectByName(name) == null;
				}
			}
		}
		return flag;
	}

	@Override
	public List<Role> getRoleList(Role role) {
		logger.info("getRoleList,role:{}",role);
		return roleMapper.getPageData(role);
	}
}
